<template>
  <div>
    <!-- 修改书籍对话框 -->
    <el-dialog title="修改图书" :visible.sync='visible' width="500px" @closed="cancel" append-to-body>
      <el-form ref="addForm" :model="addForm" label-width="80px" :rules="rules">
        <el-form-item label="图书名称" prop="name">
          <el-input v-model="addForm.name" placeholder="请输入书籍名称" />
        </el-form-item>

        <el-form-item label="作者" prop="author">
          <el-select
            v-model="AuthorValue"
            filterable
            allow-create
            default-first-option
            placeholder="请选择作者"
            @change="isAddAuthor"
            :filter-method="AuthorKeyChange"

            >
<!--            @blur="authorBlur"-->
            <el-option v-for="item in AuthorOptions" :key="item.author" :label="item.author" :value="item.authorValue">

              <span style="float: left">{{ item.author }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">编号:{{ item.authorValue }}</span>
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="出版社" prop="publish">
          <el-select
            v-model="PublishValue"
            filterable
            allow-create
            default-first-option
            placeholder="请选择出版社"
            @change="isAddPublish"
            :filter-method="PublishKeyChange"
            >
            <el-option v-for="item in PublishOptions" :key="item.publish" :label="item.publish"
              :value="item.publishValue">

              <span style="float: left">{{ item.publish }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">编号:{{ item.publishValue }}</span>
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="ISBN" prop="isbn">
          <el-input v-model="addForm.isbn" placeholder="请输入ISBN" />
        </el-form-item>

        <el-form-item label="介绍" prop="introduction">
          <el-input v-model="addForm.introduction" type="textarea" placeholder="请输入内容" />
        </el-form-item>

        <el-form-item label="语言" prop="language">
          <el-select v-model="LanguageValue" filterable allow-create default-first-option placeholder="请选择语言"
            @change="isAddLanguage">
            <el-option v-for="item in LanguageOptions" :key="item.language" :label="item.language"
              :value="item.languageValue">
            </el-option>
          </el-select>
        </el-form-item>


<!--        <el-form-item label="图书分类" prop="categoryId">-->
<!--          <el-select v-model="CategoryList"   multiple placeholder="请选择">-->
<!--            <el-option v-for="item in CategoryOptions" :key="item.value" :label="item.name" :value="item.name">-->
<!--            </el-option>-->
<!--          </el-select>-->
<!--        </el-form-item>-->

        <el-form-item label="价格" prop="price">
          <el-input v-model="addForm.price" placeholder="请输入价格" />
        </el-form-item>

        <el-form-item label="数量" prop="number">
          <el-input v-model="addForm.number" placeholder="请输入数量" />
        </el-form-item>





        <el-form-item label="位置" prop="location">
          <el-input v-model="addForm.location" placeholder="请输入位置" />
        </el-form-item>





        <!-- 上传图书封面 -->
<!--        <el-form-item label="图书封面">-->

<!--          <imageUpload @getPicUrl="handlePicUrl" :picUrl="addForm.url">-->

<!--          </imageUpload>-->


<!--        </el-form-item>-->

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm(addForm)">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
      <!-- <button @click="test">点击</button> -->
    </el-dialog>

  </div>
</template>

<script>
import { getAllBook, addBook, editBook, getDict, addDict,searchDict } from '@/api/request.js'
import imageUpload from '@/components/ManagementTable/ImageUpload.vue'
export default {
  name: "editTable",
  props: ["editData"],
  components: {
    imageUpload
  },
  mounted() {
    this.addForm = this.editData
    this.AuthorValue = this.editData.author
    this.addForm.author = this.editData.authorValue

    this.PublishValue = this.editData.publish
    this.addForm.publish = this.editData.publishValue

    this.LanguageValue = this.editData.language
    this.addForm.language = this.editData.languageValue

    this.CategoryList = this.editData.categoryName


    // this.CategoryValue = this.editData.categoryId
    // this.addForm.categoryId = this.editData.
    var tempCategory = ''
    for (var i = 0; i < this.editData.categoryValue.length; i++) {
      if (i == 0) {
        tempCategory += this.editData.categoryValue[i]
      } else {
        tempCategory = tempCategory + ',' + this.editData.categoryValue[i]
      }
    }
    this.addForm.categoryId = tempCategory;

    console.log('当前id',this.$store.state.user.userId)
  },
  data() {
    return {
      visible: true,
      //表单验证
      rules: {
        name: [{ required: true, message: '图书名不能为空', trigger: 'blur' }],
        author: [{ required: true, message: '作者不能为空', trigger: 'blur' }],
        publish: [{ required: true, message: '出版社不能为空', trigger: 'blur' }],
        isbn: [{ required: true, message: 'ISBN不能为空', trigger: 'blur' }],
        // introduction:[{required: true, message: '介绍不能为空', trigger: 'blur'}],
        language: [{ required: true, message: '语言不能为空', trigger: 'blur' }],
        price: [{ required: true, message: '请输入价格', trigger: 'blur' }],
        number: [{ required: true, message: '请输入数量', trigger: 'blur' }],
        // categoryId: [{ required: true, message: '图书分类不能为空', trigger: 'blur' }],
        location: [{ required: true, message: '请输入位置', trigger: 'blur' }],
        // updateBy: [{ required: true, message: '更新者不能为空', trigger: 'blur' }],

      },

      //添加图书表单
      addForm: {
        url: "",
        updateTime: '',
        publish: '',
        language: '',
        author: '',
        updateBy: this.$store.state.user.userId,
        categoryId: "",
      },
      // 添加出版社选择框
      PublishOptions: [],
      //出版社编号
      PublishValue: "",

      //添加字典参数
      queryAddDict: {
        type: "",
        value: [],
      },
      //添加语言选择框
      LanguageOptions: [],
      //回传的语言编号
      LanguageValue: "",
      //作者选择框
      AuthorOptions: [],
      //作者编号
      AuthorValue: '',
      UserValue:'',
      // 用户选择框
      UserOptions:[],
      //分类选项
      CategoryOptions: [],
      //分类编号
      CategoryValue: [],
      //选中分类标签
      CategoryList: [],

      //出版社字典参数
      queryPublishDict: {
        type: "publish"
      },
      //作者字典参数
      queryAuthorDict: {
        type: "author"
      },
      //语言字典参数
      queryLanguageDict: {
        type: "language"
      },
      //分类字典参数
      queryCategoryIdDict: {
        type: "category"
      },
      //用户字典参数
       queryUserDict: {
        type: "username"
      },
      //上传文件
      fileList: [],
      formData: "", // 初始化的上传
    }
  },
  created() {
    // this.getAllPublish()
    this.getAllLanguage()
    // this.getAllAuthor()
    this.getAllCategory()
    // this.getAllUser()
  },

  methods: {

    handleUpdate(){
      this.addForm.updateBy =  this.$store.state.user.userId,
      // this.addForm.updateBy =  this.UserValue
      console.log('处理更新人',this.addForm.updateBy)
    },

// 拼接分类id
    StrCategoryId() {
      var tempCategory = ''
      for (var i = 0; i < this.CategoryValue.length; i++) {
        if (i == 0) {
          tempCategory += this.CategoryValue[i]
        } else {
          tempCategory = tempCategory + ',' + this.CategoryValue[i]
        }
      }
      this.addForm.categoryId = tempCategory;
      // console.log('提交的分类',this.addForm.categoryId)

    },
     /**
     * 查询所有用户
     */
    getAllUser(){
      getDict(this.queryUserDict).then(res => {
        // console.log('查询用户接口', res)
        this.UserOptions = res.data
      }).catch(err => {
        console.log('查询出版社接口失败', err)
      })
    },
    /**
     * 查询所有出版社
     */
    getAllPublish() {
      getDict(this.queryPublishDict).then(res => {
        // console.log('查询出版社接口', res)
        this.PublishOptions = res.data
      }).catch(err => {
        console.log('查询出版社接口失败', err)
      })
    },
    /**
     * 查询所有语言
     */
    getAllLanguage() {
      getDict(this.queryLanguageDict).then(res => {
        // console.log('查询语言接口', res)
        this.LanguageOptions = res.data
      }).catch(err => {
        console.log('查询语言接口失败', err)
      })
    },

    /**
     * 查询所有作者
     */
    getAllAuthor() {
      getDict(this.queryAuthorDict).then(res => {
        // console.log('查询作者接口', res)
        this.AuthorOptions = res.data
      }).catch(err => {
        console.log('查询语言接口失败', err)
      })
    },
    /**
   * 查询所有分类
   */
    getAllCategory() {
      getDict(this.queryCategoryIdDict).then(res => {
        // console.log('查询分类接口', res)
        this.CategoryOptions = res.data
      }).catch(err => {
        console.log('查询分类接口失败', err)
      })
    },



   //模糊查询作者
   AuthorKeyChange:function(inputKey){
    console.log('inputKey',inputKey)
    if(inputKey != ''){
       searchDict({ type: "author",keyWord:inputKey}).then(res=>{
        // console.log('获取到的模糊查询',res)
        this.AuthorOptions = res.data
      }).catch(err=>{
        console.log('作者模糊查询失败')
      })
    }else{
      this.AuthorOptions =[]
    }

  },

  //出版社模糊查询
  PublishKeyChange:function(inputKey){
    if(inputKey != ''){
      searchDict({ type: "publish",keyWord:inputKey}).then(res=>{
        // console.log('获取到的模糊查询',res)
        this.PublishOptions = res.data
      }).catch(err=>{
        console.log('出版社模糊查询失败')
      })
    }else{
      this.PublishOptions = []
    }



  },
    /**
     *@functionName:     zxh
     *@description:判断是否要新增作者,如果需要则添加
     *@author: zxh
     *@date: 2024-01-09 11:24:10
    */
    isAddAuthor() {
      var add = true
      for (var i = 0; i < this.AuthorOptions.length; i++) {
        if (this.AuthorValue == this.AuthorOptions[i].authorValue) {
          add = false
          this.addForm.author = this.AuthorValue
        }
      }
      this.addForm.author = this.AuthorValue
      if (add) {
        this.$confirm('是否添加', '未查询到该作者?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          addDict({
            "type": "author",
            "value": [
              this.AuthorValue
            ]
          }).then(res => {
            console.log('添加作者成功', res)
            this.addForm.author = res.data
          }).catch(err => {
            console.log('添加作者失败')
          })
          this.$message({
            type: 'success',
            message: '添加成功!'
          });
        }).catch(() => {
          this.AuthorValue = ''
          this.AuthorOptions=[]
        });


      }

    },



    isAddPublish() {
      var add = true
      for (var i = 0; i < this.PublishOptions.length; i++) {
        if (this.PublishValue == this.PublishOptions[i].publishValue) {
          add = false
        }
      }
      this.addForm.publish = this.PublishValue
      if (add) {

        this.$confirm('此操作将添加出版社是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          addDict({
            "type": "publish",
            "value": [
              this.PublishValue
            ]
          }).then(res => {
            console.log('添加出版社成功', res)
            this.addForm.publish = res.data
          }).catch(err => {
            console.log('添加出版社失败')
          })

          this.$message({
            type: 'success',
            message: '添加成功!'
          });
        }).catch(() => {
          this.PublishValue=''
          this.PublishOptions=[]
        });
      }

    },



    isAddLanguage() {
      var add = true
      for (var i = 0; i < this.LanguageOptions.length; i++) {
        if (this.LanguageValue == this.LanguageOptions[i].languageValue) {
          add = false
        }
      }
      this.addForm.language = this.LanguageValue
      if (add) {
        this.$confirm('此操作将添加语言, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          addDict({
            "type": "language",
            "value": [
              this.LanguageValue
            ]
          }).then(res => {
            console.log('添加语言成功', res)
            this.addForm.language = res.data
          }).catch(err => {
            console.log('添加语言失败')
          })
          this.$message({
            type: 'success',
            message: '添加成功!'
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消添加'
          });
        });

      }

    },

    handleCategory(){
      // 将数组清空
      this.CategoryValue = []
      for(var i=0;i<this.CategoryOptions.length;i++){
        for(var j=0;j<this.CategoryOptions.length;j++){
          if(this.CategoryList[i] == this.CategoryOptions[j].name){
            this.CategoryValue.push(this.CategoryOptions[j].value)
          }
        }
      }
      console.log('categoryValue',this.CategoryValue)
      this.StrCategoryId()
      // console.log('提交的数据id',this.addForm.categoryId)
    },


    /** 提交按钮 */
    submitForm: function (data) {
      //点击提交时将提交时间传给addForm
      this.addForm.updateBy = this.$store.state.user.userId
      this.handleTime()
      this.$refs["addForm"].validate((valid) => {
        if (valid) {
          // if (this.addForm === this.editData) {
            // console.log('addForm',this.addForm)
            // console.log('editData',this.editData)
          // if (this.CategoryList == '') {
          //   this.$alert('未修改！', '警告', {
          //     confirmButtonText: '确定',
          //     callback: action => {
          //       this.$message({
          //         type: 'warning',
          //         message: `请修改`
          //       });
          //     }
          //   });
          // } else {
          //   this.handleCategory()
          //   this.StrCategoryId()
            editBook(data).then(res => {
              this.addForm = {}
              // 将弹窗关闭
              this.$emit("closeEditTable")
            }).catch(err => {
              console.log(err)
            })



          // }

        } else {
          console.log('提交修改失败！');
          return false;
        }
      });

    },
    /**
     * 点击取消按钮
     */
    cancel() {
      this.$emit("closeEditTable")
    },
    handleTime() {
      // 创建一个 Date 对象
      var today = new Date();

      // 获取年、月、日、时、分、秒
      var year = today.getFullYear();
      var month = today.getMonth() + 1; // 月份是从 0 开始计数的，需要加1
      var day = today.getDate();
      var hours = today.getHours();
      var minutes = today.getMinutes();
      var seconds = today.getSeconds();

      // 格式化输出
      var formattedTime = year + "-" +
        (month < 10 ? "0" : "") + month + "-" +
        (day < 10 ? "0" : "") + day + " " +
        (hours < 10 ? "0" : "") + hours + ":" +
        (minutes < 10 ? "0" : "") + minutes + ":" +
        (seconds < 10 ? "0" : "") + seconds;
      this.addForm.updateTime = formattedTime

      // console.log(this.addForm.createTime);
      // "2023-11-08 19:05:05"
    },

    // 从图片上传组件返回图片的url
    handlePicUrl(data) {
      this.addForm.url = data;
    },


    // 重置infoData
    restInfoData() {
      this.infoData = {}
    },
  },
}

</script>

<style></style>
